package fpt.edu.vn.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.ModifiableSolrParams;

/**
 * Only add space to the query if there is already something in the query.
 * 
 * @param query
 */

public class SolrQuerying {

	private void addSpaceToQuery(StringBuilder query) {
		if (query.length() > 0) {
			// Use a + sign for URL Encoding
			query.append("-");
		}
	}

	public List<Map<String, Object>> TopicSearch(int provinceId,
			int districtId, int topictype, int iPrice, int iArea, int sortby)
			throws Exception {
		// SolrServer server = new CommonsHttpSolrServer(
		// "http://localhost:8983/solr" );
		CommonsHttpSolrServer server = new CommonsHttpSolrServer(
				"http://localhost:8983/solr");
		server.setParser(new XMLResponseParser());
		StringBuilder stbquery = new StringBuilder();

		if (provinceId == 0 && districtId == 0 && topictype == 0 && iPrice == 0
				&& iArea == 0) {
			stbquery.append("*:*");
		} else {
			if (provinceId != 0) {
				addSpaceToQuery(stbquery);
				stbquery.append("ProvinceId").append(":").append(provinceId);
			}
			if (districtId != 0) {
				addSpaceToQuery(stbquery);
				stbquery.append("DistrictId").append(":").append(districtId);
			}
			if (topictype != 0) {
				addSpaceToQuery(stbquery);
				stbquery.append("TopicTypeId").append(":").append(topictype);
			}
			if (iPrice != 0) {
				addSpaceToQuery(stbquery);
				if (iPrice == 1) {
					stbquery.append("Price").append(":[* TO 2]");
				}
				if (iPrice == 2) {
					stbquery.append("Price").append(":[2 TO 4]");
				}
				if (iPrice == 3) {
					stbquery.append("Price").append(":[4 TO 6]");
				}
				if (iPrice == 4) {
					stbquery.append("Price").append(":[6 TO *]");
				}

			}
			if (iArea != 0) {
				addSpaceToQuery(stbquery);
				if (iArea == 1) {
					stbquery.append("Area").append(":[* TO 15]");
				}
				if (iArea == 2) {
					stbquery.append("Area").append(":[15 TO 20]");
				}
				if (iArea == 3) {
					stbquery.append("Area").append(":[20 TO 30]");
				}
				if (iArea == 4) {
					stbquery.append("Area").append(":[30 TO *]");
				}
			}
		}
		String s = stbquery.substring(0);
		s = s.replaceAll("-", " AND ");
		SolrQuery query = new SolrQuery(s);
		query.setParam("wt", "json");
		query.setStart(0);
		query.setRows(10000);
		if (sortby == 1) {
			query.addSortField("Price", ORDER.asc);
		} else if (sortby == 2) {
			query.addSortField("Price", ORDER.desc);
		} else if (sortby == 3) {
			query.addSortField("ViewNum", ORDER.desc);
		} else if (sortby == 4) {
			query.addSortField("Area", ORDER.desc);
		} else if (sortby == 5) {
			query.addSortField("Area", ORDER.asc);
		} else {
			query.addSortField("RenewDate", ORDER.desc);
		}

		QueryResponse response = server.query(query);
		SolrDocumentList documents = response.getResults();
		Iterator<SolrDocument> itr = documents.iterator();
		List<Map<String, Object>> lstTopic = new ArrayList<Map<String, Object>>();

		while (itr.hasNext()) {
			SolrDocument doc = itr.next();
			Map<String, Object> mapTopic = new HashMap<String, Object>();
			mapTopic.put("TopicId", doc.getFieldValue("id"));
			mapTopic.put("Title", doc.getFieldValue("Title"));
			mapTopic.put("Address", doc.getFieldValue("Address"));
			mapTopic.put("Price", doc.getFieldValue("Price"));
			mapTopic.put("Area", doc.getFieldValue("Area"));
			mapTopic.put("ViewNum", doc.getFieldValue("ViewNum"));
			mapTopic.put("DisplayName", doc.getFieldValue("DisplayName"));
			mapTopic.put("CreateDate", doc.getFieldValue("CreateDate"));
			mapTopic.put("Latitude", doc.getFieldValue("Latitude"));
			mapTopic.put("Longitude", doc.getFieldValue("Longitude"));
			mapTopic.put("DistrictName", doc.getFieldValue("DistrictName"));
			mapTopic.put("Image", doc.getFieldValue("Image"));
			mapTopic.put("DistrictId", doc.getFieldValue("DistrictId"));
			mapTopic.put("TopicTypeId", doc.getFieldValue("TopicTypeId"));
			mapTopic.put("Description", doc.getFieldValue("Description"));
			mapTopic.put("UsersId", doc.getFieldValue("UsersId"));
			mapTopic.put("ProvinceId", doc.getFieldValue("ProvinceId"));
			lstTopic.add(mapTopic);
		}
		return lstTopic;
	}

	// fulltext
	public List<Map<String, Object>> Fulltext(String strTextSearch, int sortby,
			int research) throws Exception {
		// SolrServer server = new CommonsHttpSolrServer(
		// "http://localhost:8983/solr" );
		CommonsHttpSolrServer server = new CommonsHttpSolrServer(
				"http://localhost:8983/solr");
		server.setParser(new XMLResponseParser());
		StringBuilder stbquery = new StringBuilder();

		if ("".equals(strTextSearch) || strTextSearch == null) {
			stbquery.append("*:*");
		} else {
			if (research == 0){
				strTextSearch = '"' + strTextSearch + '"';
			}else{
				strTextSearch = '(' + strTextSearch + ')';
			}
			addSpaceToQuery(stbquery);
			stbquery.append("fulltextsearch").append(":").append(strTextSearch);

		}
		SolrQuery query = new SolrQuery(stbquery.toString());
		query.setParam("wt", "json");
		query.setParam("hl", "true");
		query.setParam("pf", "fulltextsearch^100");
		query.setParam("qf", "fulltextsearch^2.3");
		query.setParam("mm", "3");
		if (research == 0 || research==1){
			query.setParam("defType", "dismax");
		}
		query.setStart(0);
		query.setRows(10000);
		if (sortby == 1) {
			query.addSortField("Price", ORDER.asc);
		} else if (sortby == 2) {
			query.addSortField("Price", ORDER.desc);
		} else if (sortby == 3) {
			query.addSortField("ViewNum", ORDER.desc);
		} else if (sortby == 4) {
			query.addSortField("Area", ORDER.desc);
		} else if (sortby == 5) {
			query.addSortField("Area", ORDER.asc);
		}else if (sortby == 6) {
			query.addSortField("RenewDate", ORDER.desc);
		}

		QueryResponse response = server.query(query);
		SolrDocumentList documents = response.getResults();
		Iterator<SolrDocument> itr = documents.iterator();
		List<Map<String, Object>> lstTopic = new ArrayList<Map<String, Object>>();

		while (itr.hasNext()) {
			SolrDocument doc = itr.next();
			Map<String, Object> mapTopic = new HashMap<String, Object>();
			mapTopic.put("TopicId", doc.getFieldValue("id"));
			mapTopic.put("Title", doc.getFieldValue("Title"));
			mapTopic.put("Address", doc.getFieldValue("Address"));
			mapTopic.put("Price", doc.getFieldValue("Price"));
			mapTopic.put("Area", doc.getFieldValue("Area"));
			mapTopic.put("ViewNum", doc.getFieldValue("ViewNum"));
			mapTopic.put("DisplayName", doc.getFieldValue("DisplayName"));
			mapTopic.put("CreateDate", doc.getFieldValue("CreateDate"));
			mapTopic.put("Latitude", doc.getFieldValue("Latitude"));
			mapTopic.put("Longitude", doc.getFieldValue("Longitude"));
			mapTopic.put("DistrictName", doc.getFieldValue("DistrictName"));
			mapTopic.put("Image", doc.getFieldValue("Image"));
			mapTopic.put("DistrictId", doc.getFieldValue("DistrictId"));
			mapTopic.put("TopicTypeId", doc.getFieldValue("TopicTypeId"));
			mapTopic.put("Description", doc.getFieldValue("Description"));
			mapTopic.put("UsersId", doc.getFieldValue("UsersId"));
			mapTopic.put("ProvinceId", doc.getFieldValue("ProvinceId"));
			lstTopic.add(mapTopic);
		}
		return lstTopic;
	}

	// end fulltext

	// fuzzy search
	public List<Map<String, Object>> TopicSearchFuzzy(double minPrice,
			double maxPrice, double s,int sortby) throws Exception {
		// SolrServer server = new CommonsHttpSolrServer(
		// "http://localhost:8983/solr" );
		CommonsHttpSolrServer server = new CommonsHttpSolrServer(
				"http://localhost:8983/solr");
		server.setParser(new XMLResponseParser());
		StringBuilder stbquery = new StringBuilder();
		addSpaceToQuery(stbquery);
		stbquery.append("Price").append(
				":[" + minPrice + " TO " + maxPrice + "]");
		addSpaceToQuery(stbquery);
		stbquery.append("Area").append(":[" + s + " TO * ]");
		String s1 = stbquery.substring(0);
		s1 = s1.replaceAll("-", " AND ");

		SolrQuery query = new SolrQuery(s1);
		System.out.println(stbquery);
		query.setParam("wt", "json");
		query.setStart(0);
		query.setRows(10000);
		if (sortby == 1) {
			query.addSortField("Price", ORDER.asc);
		} else if (sortby == 2) {
			query.addSortField("Price", ORDER.desc);
		} else if (sortby == 3) {
			query.addSortField("ViewNum", ORDER.desc);
		} else if (sortby == 4) {
			query.addSortField("Area", ORDER.desc);
		} else if (sortby == 5) {
			query.addSortField("Area", ORDER.asc);
		} else {
			query.addSortField("RenewDate", ORDER.desc);
		}

		QueryResponse response = server.query(query);
		SolrDocumentList documents = response.getResults();
		Iterator<SolrDocument> itr = documents.iterator();
		List<Map<String, Object>> lstTopic = new ArrayList<Map<String, Object>>();

		while (itr.hasNext()) {
			SolrDocument doc = itr.next();
			Map<String, Object> mapTopic = new HashMap<String, Object>();
			mapTopic.put("TopicId", doc.getFieldValue("id"));
			mapTopic.put("Title", doc.getFieldValue("Title"));
			mapTopic.put("Address", doc.getFieldValue("Address"));
			mapTopic.put("Price", doc.getFieldValue("Price"));
			mapTopic.put("Area", doc.getFieldValue("Area"));
			mapTopic.put("ViewNum", doc.getFieldValue("ViewNum"));
			mapTopic.put("DisplayName", doc.getFieldValue("DisplayName"));
			mapTopic.put("CreateDate", doc.getFieldValue("CreateDate"));
			mapTopic.put("Latitude", doc.getFieldValue("Latitude"));
			mapTopic.put("Longitude", doc.getFieldValue("Longitude"));
			mapTopic.put("DistrictName", doc.getFieldValue("DistrictName"));
			mapTopic.put("Image", doc.getFieldValue("Image"));
			mapTopic.put("DistrictId", doc.getFieldValue("DistrictId"));
			mapTopic.put("TopicTypeId", doc.getFieldValue("TopicTypeId"));
			mapTopic.put("Description", doc.getFieldValue("Description"));
			mapTopic.put("UsersId", doc.getFieldValue("UsersId"));
			mapTopic.put("ProvinceId", doc.getFieldValue("ProvinceId"));
			lstTopic.add(mapTopic);
		}
		return lstTopic;
	}

	public void updateDataFromMysqlToSolr() throws Exception {
		CommonsHttpSolrServer server = new CommonsHttpSolrServer(
				"http://localhost:8983/solr");
		ModifiableSolrParams params = new ModifiableSolrParams();
		params.set("command", "full-import");
		params.set("clean", "true");
		QueryRequest request = new QueryRequest(params);
		request.setPath("/dataimport");
		server.request(request);

	}

}
